package com.caesar.exer1_2;

import java.util.Stack;

/**
 * @author caesar
 * @date 2025/7/18
 * @Description:括号检查，判断括号是否正确匹配
 * 给定一个包含圆括号，方括号，花括号，判断括号是否正确匹配
 * @apiNote
 */
public class exer1 {
    public static void main(String[] args) {
        String test1 = "{[a * (b + c)] / 2} * (a + b)";
        System.out.println(test1 +"表达式"+ ( check(test1)?"括号正确":"括号错误"));
        String test2 = "{[a * ( b + c] / 2)}";
        System.out.println(test2 +"表达式"+ ( check(test2)?"括号正确":"括号错误"));
    }

    public static boolean check(String str){
        Stack<Character> stack = new Stack<>();

        char[] chars = str.toCharArray();
        boolean flag = true;
        for (char ch : chars) {
            if (ch == '(' || ch == '[' || ch == '{') {
                stack.push(ch); //遇到(、[、{ 开括号时，压入栈
            } else if (ch == ')' || ch == ']' || ch == '}') {
                if (stack.isEmpty()) {
                    return false; // 如果栈为空，说明没有匹配的开括号
                }
                char open = stack.pop(); //弹出栈顶元素
                char close = ch;
                //判断栈顶元素与当前 闭括号 是否是一对
                if (!((open == '(' && close == ')') ||
                        (open == '[' && close == ']') ||
                        (open == '{' && close == '}'))) {
                    return false; // 开闭括号不匹配
                }
            }
        }
        return stack.isEmpty();
    }
}
